<?php namespace App\Controllers;

use App\App;

class Vote extends App
{
    public function __construct()
    {
        parent::__construct();
        if (!$this->user) {
            $this->showJson("您还未登录，请登录后投票...", "Error");
        }
    }

    public function index()
    {
        $storyID = $this->request->post('story');
        $value = $this->request->post('value');

        $voteModel = new \App\Models\Vote();
        $vote = $voteModel->reset($this->user['id']);
        $storyModel = new \App\Models\Story();
        if ($vote['num'] < $value) {
            $this->showJson("您现在还有票数 - {$vote['num']}，<br/>请不要超出票数。", "Error");
        }
        $story = $storyModel->find($storyID);
        $storyModel->set("vote", $story['vote'] + $value)->where('id', $storyID)->update();
        $voteModel->set("num", $vote['num'] - $value)->where('user', $this->user['id'])->update();
        $this->showJson("感谢您的投票。", "Success");
    }
}